/*******************************************************************************************************

Table 1: Most common petition topics

*******************************************************************************************************/

clear all

*Set directory path
cd "C:\Users\tsa23\Documents\petitions\replication files"

*Read in data with topics for the borough constituencies
use dta\topics_boroughs_rep
sort year topics

*define the periods
gen byte p1820_24 = inrange(year,1820,1824)
gen byte p1825_29 = inrange(year,1825,1829)
gen byte p1830_32 = inrange(year,1830,1832)
gen byte p1833_35 = inrange(year,1833,1835)
gen byte p1836_38 = inrange(year,1836,1838)

* Build a single categorical period variable from the dummies
capture drop period
gen byte period = .                         // start missing
replace period = 0 if p1820_24 == 1         // base period
replace period = 1 if p1825_29 == 1
replace period = 2 if p1830_32 == 1
replace period = 3 if p1833_35 == 1
replace period = 4 if p1836_38 == 1

* (Optional) sanity check: exactly one period dummy per row
*assert inlist(p1820_24 + p1825_29 + p1830_32 + p1833_35 + p1836_38, 0, 1)
* If you expect full coverage by these five bins, use:
*assert p1820_24 + p1825_29 + p1830_32 + p1833_35 + p1836_38 == 1

* Labels
label define period_lbl 0 "1820–24" 1 "1825–29" 2 "1830–32" 3 "1833–35" 4 "1836–38"
label values period period_lbl

* Loop over existing period values
levelsof period, local(periods)

foreach p of local periods {
    * Grab the value-label text for nice headers (if period has one)
    local vlab : value label period
    local plab ""
    if "`vlab'" != "" {
        local plab : label `vlab' `p'
    }

    di as txt "===================="
    di as res "Period `p' `=cond("`plab'"!="","(`plab')","")'"

    preserve
        keep if period == `p'
        *tabulate topics
        contract topics
        gsort -_freq
        list topics _freq if _freq > 20, noobs
    restore
}


